package com.zfzs.post.service.impl;

import cn.hutool.core.util.IdUtil;
import com.zfzs.post.common.bean.ResponseCode;
import com.zfzs.post.exception.BadRequestException;
import com.zfzs.post.model.dto.VCodeDTO;
import com.zfzs.post.modules.agent.domain.Agent;
import com.zfzs.post.modules.agent.domain.AgentBank;
import com.zfzs.post.modules.agent.service.AgentBankService;
import com.zfzs.post.modules.agent.service.AgentService;
import com.zfzs.post.modules.agent.service.dto.AgentDTO;
import com.zfzs.post.modules.agent.service.mybatis.IAgentService;
import com.zfzs.post.modules.backstage.domain.UserInfo;
import com.zfzs.post.modules.backstage.service.BackStageUserService;
import com.zfzs.post.service.JwtUserDetailsService;
import com.zfzs.post.service.RedisService;
import com.zfzs.post.service.SmsService;
import com.zfzs.post.sms.SendSms;
import com.zfzs.post.sms.SmsType;
import com.zfzs.post.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * 短信信息
 *
 * @author: ck
 * @create: 2019/9/9/10:17
 **/
@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    private AgentService agentService;
    @Autowired
    private RedisService redisService;

    @Value("${sms.expiration}")
    private Long expiration;

    @Autowired
    private JwtUserDetailsService jwtUserDetailsService;

    @Autowired
    private BackStageUserService backStageUserService;

    @Autowired
    private IAgentService iAgentService;

    @Autowired
    private AgentBankService agentBankService;

    @Override
    public Map<String,String> sendRegisteCode(VCodeDTO dto) {
        Map<String,String> map = new HashMap<>();
        Long channelId = dto.getChannelId();
        String phone = dto.getPhone();
        Agent agent = agentService.findByPhoneAndChannelId(phone,channelId);
        if (agent != null) {
            throw new BadRequestException(ResponseCode.REPEAT_USER_FAIL);
        }
        String uuid = sendSmsCode(channelId,phone, SmsType.REGISTER.getInfo());
        map.put("uuid",uuid);
        return map;
    }

    @Override
    public Map<String,String> sendLoginCode(VCodeDTO dto) {
        Map<String,String> map = new HashMap<>();
        Long channelId = dto.getChannelId();
        String phone = dto.getPhone();
        Agent agent = agentService.findByPhoneAndChannelId(phone,channelId);
        if (agent == null) {
            throw new BadRequestException(ResponseCode.NO_USER_FAIL);
        }
        if (agent.getIsEnabled()) {
            throw new BadRequestException(ResponseCode.USER_ENABLED_FAIL);
        }
        String uuid =  sendSmsCode(channelId, phone, SmsType.LOGIN.getInfo());
        map.put("uuid",uuid);
        return map;
    }

    @Override
    public Map<String,String> sendForgetPwdCode(VCodeDTO dto) {
        Map<String,String> map = new HashMap<>();
        String phone = dto.getPhone();
        Long channelId = dto.getChannelId();
        Agent agent = agentService.findByPhoneAndChannelId(phone,channelId);
        if (agent == null) {
            throw new BadRequestException(ResponseCode.NO_USER_FAIL);
        }
        if (agent.getIsEnabled()) {
            throw new BadRequestException(ResponseCode.USER_ENABLED_FAIL);
        }
        String uuid = sendSmsCode(agent.getChannelId(), phone, SmsType.FORGET_PWD.getInfo());
        map.put("uuid",uuid);
        return map;
    }

    @Override
    public Map<String, String> sendUpdatePwdCode() {
        Map<String,String> map = new HashMap<>();
        AgentDTO agent = jwtUserDetailsService.getAgentInfo();
        String phone = agent.getPhone();
        if (agent == null) {
            throw new BadRequestException(ResponseCode.NO_USER_FAIL);
        }
        if (agent.getIsEnabled()) {
            throw new BadRequestException(ResponseCode.USER_ENABLED_FAIL);
        }
        String uuid = sendSmsCode(agent.getChannelId(), phone, SmsType.UPDATE_PWD.getInfo());
        map.put("uuid",uuid);
        return map;
    }

    @Override
    public Map<String, String> updateWithdrawPwdCode() {
        Map<String,String> map = new HashMap<>();
        AgentDTO agent = jwtUserDetailsService.getAgentInfo();
        String phone = agent.getPhone();
        if (agent == null) {
            throw new BadRequestException(ResponseCode.NO_USER_FAIL);
        }
        if (agent.getIsEnabled()) {
            throw new BadRequestException(ResponseCode.USER_ENABLED_FAIL);
        }
        String uuid = sendSmsCode(agent.getChannelId(), phone, SmsType.UPDATE_WITHDRAW_PWD.getInfo());
        map.put("uuid",uuid);
        return map;
    }

    @Override
    public Map<String, String> forgetWithdrawPwdCode(VCodeDTO dto) {
        Map<String,String> map = new HashMap<>();
        String phone = dto.getPhone();
        Long channelId = dto.getChannelId();
        Agent agent = agentService.findByPhoneAndChannelId(phone,channelId);
        if (agent == null) {
            throw new BadRequestException(ResponseCode.NO_USER_FAIL);
        }
        if (agent.getIsEnabled()) {
            throw new BadRequestException(ResponseCode.USER_ENABLED_FAIL);
        }
        String uuid = sendSmsCode(agent.getChannelId(), phone, SmsType.FORGET_WITHDRAW_PWD.getInfo());
        map.put("uuid",uuid);
        return map;
    }

    @Override
    public Map<String,String> sendVerified(VCodeDTO dto) {
        Map<String,String> map = new HashMap<>();
        AgentDTO agent = jwtUserDetailsService.getAgentInfo();
        if (agent.getIsEffective() == 1 || agent.getIsEffective() == 2) {
            throw new BadRequestException("正在审核或者已经完成认证");
        }
        String phone = dto.getPhone();
        if(StringUtils.isBlank(phone)){
            throw new BadRequestException("渠道ID或者预留手机号码不能为空");
        }
        //校验手机号码是否存在
        int count = iAgentService.findByPhoneAndChannel(phone,agent.getChannelId());
        if(count > 0){
            throw new BadRequestException("此预留手机号码已经被使用");
        }
        String uuid = sendSmsCode(agent.getChannelId(), phone, SmsType.VERIFIED.getInfo());
        map.put("uuid",uuid);
        return map;
    }

    @Override
    public Map<String,String> sendUpdateBankNo(VCodeDTO dto) {
        Map<String,String> map = new HashMap<>();
        String phone = dto.getPhone();
        AgentDTO agent = jwtUserDetailsService.getAgentInfo();
        if (agent.getIsEffective() == 0) {
            throw new BadRequestException("您还未完成实名认证操作");
        }
        AgentBank bank = agentBankService.findById(agent.getId());
        String agentPhone = bank.getPhone();
        if(!StringUtils.equals(agentPhone,phone)){
            throw new BadRequestException("预留手机号码不一致");
        }
        String uuid = sendSmsCode(agent.getChannelId(), phone, SmsType.UPDATE_BANK_NO.getInfo());
        map.put("uuid",uuid);
        return map;
    }

    @Override
    public Map<String,String> sendUpdateIdCardNo() {
        Map<String,String> map = new HashMap<>();
        AgentDTO agent = jwtUserDetailsService.getAgentInfo();
        if (agent.getIsEffective() == 0) {
            throw new BadRequestException("您还未完成实名认证操作");
        }
        String uuid = sendSmsCode(agent.getChannelId(), agent.getPhone(), SmsType.UPDATE_ID_CARD_NO.getInfo());
        map.put("uuid",uuid);
        return map;
    }

    @Override
    public Map<String,String> sendUpdatePhone(VCodeDTO dto) {
        Map<String,String> map = new HashMap<>();
        String phone = dto.getPhone();
        AgentDTO agent = jwtUserDetailsService.getAgentInfo();
        //查询手机号是否存在
        if (agent.getPhone().equals(phone)) {
            throw new BadRequestException("手机号码和本人手机号码相同");
        }
        Agent agentDTO = agentService.findByPhoneAndChannelId(phone,agent.getChannelId());
        if (agentDTO != null) {
            throw new BadRequestException(ResponseCode.REPEAT_USER_FAIL);
        }
        String uuid = sendSmsCode(agent.getChannelId(), phone, SmsType.UPDATE_PHONE.getInfo());
        map.put("uuid",uuid);
        return map;
    }

    @Override
    public Map<String,String> sendUpdateIdCardName() {
        Map<String,String> map = new HashMap<>();
        AgentDTO agent = jwtUserDetailsService.getAgentInfo();
        if (agent.getIsEffective() == 0) {
            throw new BadRequestException("您还未完成实名认证操作");
        }
        String uuid = sendSmsCode(agent.getChannelId(), agent.getPhone(), SmsType.UPDATE_ID_CARD_NAME.getInfo());
        map.put("uuid",uuid);
        return map;
    }

    @Override
    public Map<String, String> sendUpdateWithdraw(VCodeDTO dto) {
        Map<String,String> map = new HashMap<>();
        String phone = dto.getPhone();
        AgentDTO agent = jwtUserDetailsService.getAgentInfo();
        if (agent.getIsEffective() == 0) {
            throw new BadRequestException("您还未完成实名认证操作");
        }
        AgentBank bank = agentBankService.findById(agent.getId());
        String agentPhone = bank.getPhone();
        if(!StringUtils.equals(agentPhone,phone)){
            throw new BadRequestException("预留手机号码不一致");
        }
        String uuid = sendSmsCode(agent.getChannelId(), phone, SmsType.UPDATE_WITHDRAW.getInfo());
        map.put("uuid",uuid);
        return map;
    }

    @Override
    public String sendSmsCode(Long channelId, String phone, String smsTemplayes) {
        //生成uuid
        String uuid = IdUtil.simpleUUID();
        try {
            UserInfo user = backStageUserService.findById(channelId);
            System.out.println(user.getUsername());
            //随机生成验证
            String vCode = StringUtils.getRandomNumberString(6);
            redisService.saveSmsCode(uuid, expiration, vCode);
            SendSms.sendEMASms(user.getNickname(),phone, vCode, smsTemplayes);
        } catch (UnsupportedEncodingException e) {
            throw new BadRequestException(ResponseCode.SEND_CODE__ERROR_FAIL);
        }
        return uuid;
    }



    @Override
    public void verifiedCode(String uuid, String vCode) {
        String code = redisService.getCodeVal(uuid);
        if (StringUtils.isEmpty(code)) {
            throw new BadRequestException(ResponseCode.V_CODE_TIME_OUT_FAIL);
        }
        if (!StringUtils.equals(vCode, code)) {
            throw new BadRequestException(ResponseCode.V_CODE_ERROR_FAIL);
        }
    }

    @Override
    public void sendMessage(Long channelId, String phone, String content) {
        try {
            UserInfo user = backStageUserService.findById(channelId);
            System.out.println(user.getUsername());
            //随机生成验证
            SendSms.sendEMASms(user.getNickname(),phone, "", content);
        } catch (UnsupportedEncodingException e) {
            throw new BadRequestException(ResponseCode.SEND_CODE__ERROR_FAIL);
        }
    }

    @Override
    public void verifiedRegisterCode(Map<String, Object> params) {
        Object uuid = params.get("uuid");
        Object vCode = params.get("vCode");
        if(uuid == null || vCode == null){
            throw new BadRequestException(ResponseCode.V_CODE_ERROR_FAIL);
        }
        verifiedCode(uuid.toString(),vCode.toString());
    }
}
